package com.dormitory.javadormitory.common;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.dormitory.javadormitory.exception.CustomException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Date;

public class JwtTokenUtils {

    private static final Logger logger = LoggerFactory.getLogger(JwtTokenUtils.class);

    private static final String SECRET = "your_secret_key"; // 在实际应用中，这个密钥应该保密并且足够复杂
    private static final long EXPIRE_TIME = 86400L; // Token有效期1天

    //生成token
    public static String generateToken(String userId) {
        try {
            Date now = new Date();
            Algorithm algorithm = Algorithm.HMAC256(SECRET);
            return JWT.create()
                    .withClaim("userId", userId)
                    .withIssuedAt(new Date(System.currentTimeMillis()))
                    .withExpiresAt(new Date(System.currentTimeMillis() + EXPIRE_TIME * 1000))
                    .sign(algorithm);
        } catch (Exception e) {
            logger.error("Token生成失败", e);
            return null;
        }
    }


    //通过Token获取用户id
    public static String getUserIdFromToken(String token) {
        try {
            DecodedJWT jwt = JWT.decode(token);
            return jwt.getClaim("userId").asString();
        } catch (Exception e) {
            logger.error("Token解析失败", e);
            return null;
        }
    }

    //验证token
    public static boolean validateToken(String token) {
        try {
            Algorithm algorithm = Algorithm.HMAC256(SECRET);
            JWT.require(algorithm).build().verify(token);
            return true;
        } catch (Exception e) {
//            logger.error("Token验证失败", e);
            return false;
        }

    }
}